﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public class utils
    {
        public static DataTable executeSql(string sql, string filtro)
        {
            SqlCommand cm = null;
            SqlDataAdapter da;
            SqlConnection conn = Conexao.Instance.getConnection();
            DataSet ds = new DataSet();

            try
            {
                cm = new SqlCommand(sql, conn);

                cm.Parameters.Add("@nome", System.Data.SqlDbType.VarChar, 128);
                cm.Parameters.Add("@id", System.Data.SqlDbType.Int);

                cm.Parameters[0].Value = filtro;

                cm.Parameters[1].Value = Convert.ToInt16(filtro);
                da = new SqlDataAdapter(cm);
                da.Fill(ds);

                conn.Close();

            }
            catch (Exception ex)
            {
                conn.Close();
                throw new Exception(ex.Message);
            }
            return ds.Tables[0];
        }        

        public static bool Login(string sql, string nome, string senha)
        {
            SqlCommand cm;
            SqlConnection conn = new SqlConnection(); ;
            bool result;

            try
            {
                conn = Conexao.Instance.getConnection();

                cm = new SqlCommand(sql, conn);
                cm.Parameters.Add("@nome", System.Data.SqlDbType.VarChar, 128);
                cm.Parameters.Add("@senha", System.Data.SqlDbType.VarChar, 32);

                cm.Parameters[0].Value = nome;
                cm.Parameters[1].Value = senha;

                conn.Open();

                result = (((int)cm.ExecuteScalar()) > 0);

                conn.Close();
            }
            catch (Exception ex)
            {
                conn.Close();
                throw new Exception(ex.Message);
            }
            return result;
        }

        public static DataTable returnDataTable(string sql)
        {
            SqlCommand cm;
            SqlDataAdapter da;
            SqlConnection conn = Conexao.Instance.getConnection();
            DataSet ds = new DataSet();

            try
            {
                cm = new SqlCommand(sql, conn);
                da = new SqlDataAdapter(cm);
                da.Fill(ds);

                conn.Close();
            }
            catch (Exception ex)
            {
                conn.Close();
                throw new Exception(ex.Message);
            }
            return ds.Tables[0];
        }
    }
}
